"use strict";
const _ = require("lodash");
const Cron = require("moleculer-cron");
const osSystem = require("os");

module.exports = {
	name: "cron",
	version:1,
	mixins: [Cron],
	dependencies:[],
	crons:[{
		name: "disable_timeout",   //检查超时任务，将其设置为任务状态已完成的失败任务
		cronTime: '0 * * * * *',
		onTick: async function() {
			let projectName = this.getLocalService("v1.cron").settings.projectName;
			this.waitForServices(["v1.schedule"]).then(async () => {
				await this.call('v1.schedule.updateTaskTimeoutFailure',{ timeout:5*60*1000, namespace:this.namespace, projectName:projectName, taskName:"cron_example",},{timeout:0}); //here 'this' is broker
			}).catch(err => {
				this.logger.error(err);
			});
		},
		manualStart: true,// true 手动触发, false 系统调度
		timeZone: 'Asia/Shanghai'
	},{
		name: "cron_example",
		cronTime: '0 */2 * * * *',  // 十分钟执行一次
		onTick: async function() {
			let projectName = this.getLocalService("v1.cron").settings.projectName;
			let job = this.getJob("cron_example");
			let task = undefined;
			this.waitForServices(["v1.schedule"]).then(async () => {
				let taskInfo = {
					namespace:this.namespace,
					projectName:projectName,
					taskName:job.name,
					hostName:osSystem.hostname(),
					nodeId:this.nodeID,
					ppid:process.ppid,
					pid:process.pid
				};
				task = await this.call('v1.schedule.robTask',taskInfo,{timeout:0}); //here 'this' is broker
				if(task != undefined) {//抢到任务
					// do something

					await this.call('v1.schedule.updateTaskFinished',{id:task.id,isSuccess:true}); //here 'this' is broker
				}
			}).catch(async (err) => {
				this.logger.error(err);
				if(task != undefined){
					await this.call('v1.schedule.updateTaskFinished',{id:task.id,isSuccess:false});
				}
			});
		},
		runOnInit: async function() {
			console.log("cron_example job is created");
		},
		manualStart: true,
		timeZone: 'Asia/Shanghai'
	}],

	settings:{
		projectName:"moleculer-example",
		timeout:5 * 60 * 1000, //任务超时设置 单位毫秒
	},

	/**
	 * Actions
	 */
	actions: {

	},

	/**
	 * Events
	 */
	events: {

	},

	/**
	 * Methods
	 */
	methods: {



	},

	/**
	 * Service created lifecycle event handler
	 */
	created() {

	},

	/**
	 * Service started lifecycle event handler
	 */
	async started() {
		/**
		 * 向任务表注册任务
		 */
		this.broker.waitForServices(["v1.task"]).then(async () => {
			let projectName = this.broker.getLocalService("v1.cron").settings.projectName;
			await this.broker.call('v1.task.createEntity',{namespace:this.broker.namespace,projectName:projectName,taskName:"cron_example",description:"定时任务demo"});
		}).catch(async (err) => {
			this.logger.error(err);
		});
	},

	/**
	 * Service stopped lifecycle event handler
	 */
	async stopped() {

	}
};
